<?php

namespace app\controller;

use app\services\Jwt;
use app\services\RedisQueue;
use app\services\WechatPayService;
use plugin\admin\app\model\Good;
use plugin\admin\app\model\Order;
use plugin\admin\app\model\User;
use support\Request;

class GoodsController
{
    public function detail(Request $request)
    {
        $id = $request->get('id');
        $goods = Good::where('unique_id',$id)->first();
        if (!empty($goods['info'])){
            $baseUrl = 'http://car.ydk1.cn';
            $goods['info'] = preg_replace_callback('/<img\s+src="([^"]+)"/i', function($matches) use ($baseUrl) {
                $src = $matches[1];
                // 检查是否为相对路径
                if (strpos($src, 'http') !== 0) {
                    $src = $baseUrl . $src;
                }
                // 添加 width="100%" 属性
                return '<img src="' . htmlspecialchars($src) . '" width="100vw"';
            }, $goods['info']);
            $goods['orderInfoName'] = '互助';
            $goods['orderInfoUrl'] = 'https://car.ydk1.cn/index/carOrder?page=1&goods_id='.$goods['id'];
        }
        return json([
            'code'=>0,
            'data'=>$goods
        ]);

    }

    public function orderList(Request $request)
    {
        $token = $request->header('token','');
        $res = Jwt::verifyjwt($token);
        if (!$res['status']){
            return json(['code'=>999,'msg'=>$res['msg']]);
        }
        $type = $request->get('type');
        $where = [];
        if (!empty($type)){
            if ($type == 1){
                $where[] = ['is_pay','=',1];
            }
            if ($type == 2){
                $where[] = ['is_reward','=',1];
            }
        }
        $user = User::where('id',$res['id']??'')->first();
        if (empty($user)){
            return json(['code'=>999,'msg'=>'请重新登录']);
        }
        $order = Order::where('user_id',$user->id)->where($where)->with('goodsInfo')->orderBy('id','desc')->get()->toArray();
        return json(['code'=>0,'data'=>$order]);
    }

    public function addOrder(Request $request)
    {
        $token = $request->header('token','');
        $res = Jwt::verifyjwt($token);
        if (!$res['status']){
            return json(['code'=>999,'msg'=>$res['msg']]);
        }
        $data = $request->post();
        $data['user_id'] = $res['id'];
        // 查询下单商品
        $goods = Good::where('unique_id',$data['unique_id'])->first();
        if (empty($goods)){
            return json(['code'=>1,'msg'=>'商品不存在']);
        }
        $user = User::where('id',$data['user_id'])->first();
        // 生成订单号
        $sn = Order::getSn();
        $rake_price = $goods->price * ($goods->proportion / 100);
        Order::create([
            'sn'=>$sn,
            'user_id'=>$data['user_id'],
            'mobile' => $user->mobile,
            'goods_id' => $goods->id,
            'rake_price' => $rake_price,
            'reward_total_price' => $goods->price,
            'order_create_time' => date('Y-m-d H:i:s'),
            'pay_method' => $data['pay_method']??1,
            'sesame_fraction' => $user->sesame_fraction??750,
            'name' => $data['name'],
            'identity_card' => $data['identity_card'],
            'identity_card_img' => $data['identity_card_img'],
            'identity_card_back_img' => $data['identity_card_back_img']??'',
            'driving_license' => $data['driving_license']??''
        ]);
        return json(['code'=>0,'msg'=>'下单成功','data'=>['sn'=>$sn]]);
    }

    public function wechatPay(Request $request)
    {
        $token = $request->header('token','');
        $res = Jwt::verifyjwt($token);
        if (!$res['status']){
            return json(['code'=>999,'msg'=>$res['msg']]);
        }
        $params = $request->post();
        if (empty($params['sn'])){
            return json(['code'=>1,'msg'=>'参数错误']);
        }
        $order = Order::where('sn',$params['sn'])->first();
        if (empty($order)) {
            return json(['code' => 1, 'msg' => '订单不存在']);
        }
        if ($order->is_pay == 1){
            return json(['code' => 1, 'msg' => '订单已支付']);
        }
        $user = User::where('id',$res['id'])->first();
        if (empty($user->openid)){
            return json(['code' => 999, 'msg' => '请先授权登录']);
        }
        $result = WechatPayService::orderUnify($user->openid,$order->goods_id,$order);
        if (!$result){
            return json(['code' => 1, 'msg' => '支付失败']);
        }
//        if ($result['result_code']!= 'SUCCESS'){
//            return json(['code' => 1, 'msg' => '支付失败']);
//        }
        return json(['code' => 0,'msg' => '请求成功','data'=>json_decode($result,true)]);
//        // 先支付成功
//        $order->is_pay = 1;
//        $order->pay_time = date('Y-m-d H:i:s');
//        $order->save();
//        RedisQueue::orderNotify($params);
//        return json(['code' => 0,'msg' => '支付成功']);
    }

}